package org.example.struct.array;

import com.alibaba.fastjson.JSON;

/**
 * @author liyishan
 * @date 2023/7/18 09:13
 * @apiNote
 */

public class Test00053MaxSubArray {
    public static void main(String[] args) {
        int[] a = new int[]{1, 2, -3, 4, 5, 6};
        int count = maxSubArray(a);
        System.out.println(count + "  array:" + JSON.toJSON(a));
    }

    /**
     * 方法一 动态规划
     * @param nums
     * @return
     * 时间复杂度 O(N)    空间复杂度  O(1)
     */
    public static int test1(int[] nums) {
        int sum = 0;
        int max = nums[0];
        for(int x:nums){
            sum = Math.max(sum+x,x);
            max = Math.max(max,sum);
        }
        return max;
    }

//todo-------------------------------方法二  分治 ------------------------------------
    class Status {
        public int lSum, rSum, mSum, iSum;

        public Status(int lSum, int rSum, int mSum, int iSum) {
            this.lSum = lSum;
            this.rSum = rSum;
            this.mSum = mSum;
            this.iSum = iSum;
        }
    }

    public static int maxSubArray(int[] nums) {
        Test00053MaxSubArray test = new Test00053MaxSubArray();
        return test.getInfo(nums, 0, nums.length - 1).mSum;
    }

    public Status getInfo(int[] a, int l, int r) {
        if (l == r) {
            return new Status(a[l], a[l], a[l], a[l]);
        }
        int m = (l + r) >> 1;
        Status lSub = getInfo(a, l, m);
        Status rSub = getInfo(a, m + 1, r);
        return pushUp(lSub, rSub);
    }

    public Status pushUp(Status l, Status r) {
        int iSum = l.iSum + r.iSum;
        int lSum = Math.max(l.lSum, l.iSum + r.lSum);
        int rSum = Math.max(r.rSum, r.iSum + l.rSum);
        int mSum = Math.max(Math.max(l.mSum, r.mSum), l.rSum + r.lSum);
        return new Status(lSum, rSum, mSum, iSum);
    }
//todo-------------------------------方法二  分治 ------------------------------------



}
